<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\ColumnRecommendDataRequest;
use App\Models\Application\Columnrec;
use App\Models\Application\ColumnRecommendData;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\Column;
use App\Models\Entity\Column\ColumnFun;
use App\Models\Entity\Column\Data;
use App\Models\Entity\Column\Subcolumn;
use App\Models\Application\Muticolumn;

use App\Repositories\Application\ColumnRecommendDataRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Schema;
use Response;
use Validator;

class ColumnRecommendDataController extends Controller
{
    use ModelForm;

    /** @var  ColumnRecommendDataRepository */
    private $columnRecommendDataRepository;

    public function __construct(ColumnRecommendDataRepository $columnRecommendDataRepo)
    {
        $this->columnRecommendDataRepository = $columnRecommendDataRepo;
    }

    /**
     * Display a listing of the ColumnRecommendData.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $columnrecId = $request->get('columnrec_id');

        if (!empty($columnrecId)) {
            $columnrec = Columnrec::find($columnrecId);
            if (empty($columnrec)) {
                Flash::error(__('application.columnrecs.not_found'));

                return redirect(route('application.columnrecs.index'));
            }
        }

        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('application.column_recommend_datas.index_header'));
            $content->description(__('application.column_recommend_datas.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new ColumnRecommendData.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.column_recommend_datas.create_header'));
            $content->description(__('application.column_recommend_datas.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created ColumnRecommendData in storage.
     *
     * @param ColumnRecommendDataRequest $request
     *
     * @return Response
     */
    public function store(ColumnRecommendDataRequest $request)
    {
        $input = $request->all();

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.column_recommend_data');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['img'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $columnRecommendData = $this->columnRecommendDataRepository->create($input);

        Flash::success(__('application.column_recommend_datas.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.column_recommend_datas.index'));

    }

    /**
     * Display the specified ColumnRecommendData.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $columnRecommendData = $this->columnRecommendDataRepository->findWithoutFail($id);

        if (empty($columnRecommendData)) {
            Flash::error(__('application.column_recommend_datas.not_found'));

            return redirect(route('application.column_recommend_datas.index'));
        }

        return view('application.column_recommend_datas.show')->with('columnRecommendData', $columnRecommendData);

    }

    /**
     * Show the form for editing the specified ColumnRecommendData.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $columnRecommendData = $this->columnRecommendDataRepository->findWithoutFail($id);

        if (empty($columnRecommendData)) {
            Flash::error(__('application.column_recommend_datas.not_found'));

            return redirect(route('application.column_recommend_datas.index'));
        }

        return Admin::content(function (Content $content) use ($id, $columnRecommendData) {

            $content->header(__('application.column_recommend_datas.edit_header'));
            $content->description(__('application.column_recommend_datas.edit_description'));

            $content->body($this->form()->edit($id));
            $content->row(view('application.column-recommend-datas.edit', ['data_id' => $columnRecommendData->data_id, 'resource_data_id' => $columnRecommendData->resource_data_id]));

        });
    }

    /**
     * Update the specified ColumnRecommendData in storage.
     *
     * @param  int              $id
     * @param ColumnRecommendDataRequest $request
     *
     * @return Response
     */
    public function update($id, ColumnRecommendDataRequest $request)
    {
        $columnRecommendData = $this->columnRecommendDataRepository->findWithoutFail($id);

        if (empty($columnRecommendData)) {
            Flash::error(__('application.column_recommend_datas.not_found'));

            return redirect(route('application.column_recommend_datas.index'));
        }
        $input = $request->all();

        // 如果删除原图
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl       = $columnRecommendData->img;
            $uploadConfig = config('custom.base.upload.column_recommend_data');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $rootDir      = config('filesystems.disks.' . $driver . '.upload');
            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $columnRecommendData->img = null;
                $columnRecommendData->save();
            }
            return response()->json(['message' => '删除成功', 'status' => true]);
        }

        $sValidators = [
            'resource_data_id' => 'required',

        ];

        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), $validators, [
            'required' => ':attribute 不能为空',
        ], [
            'resource_data_id' => '资源ID',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.column_recommend_data');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath     = $rootDir . '/' . $dir . '/' . $newImageName;
                $input['img'] = $fullPath;
                $flag         = Storage::disk($driver)->delete($columnRecommendData->img);
                $bool         = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $columnRecommendData = $this->columnRecommendDataRepository->update($input, $id);

        Flash::success(__('application.column_recommend_datas.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.column_recommend_datas.index'));
    }

    /**
     * Remove the specified ColumnRecommendData from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->columnRecommendDataRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.column_recommend_datas.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $columnRecommendData = $this->columnRecommendDataRepository->findWithoutFail($id);

        if (empty($columnRecommendData)) {
            Flash::error(__('application.column_recommend_datas.not_found'));

            return redirect(route('application.column_recommend_datas.index'));
        }

        if ($flag = $this->columnRecommendDataRepository->delete($id)) {

            return response()->json(['message' => __('application.column_recommend_datas.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(ColumnRecommendData::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '推荐数据名称');
            $form->text('title', '显示名称');
            $datas = Data::pluck('title', 'id');
            $form->select('data_id', '数据类型')->options($datas)->load('resource_data_id', route('application.column_recommend_datas.datas.resources'), 'id', 'name');
            $form->select('resource_data_id', '选择数据')->options();
            $form->textarea('onclick', 'onclick事件');

            $form->image('img', '图片')->removable();
            $form->number('order', '排序');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(ColumnRecommendData::class, function (Grid $grid) use ($request) {
            if (!empty($request->get('columnrec_id'))) {
                $columnRecommendDataIds = DB::table('columnrec_column_recommend_datas')->where(['columnrec_id' => $request->input('columnrec_id')])->pluck('column_recommend_data_id')->toArray();
                $grid->model()->whereIn('id', $columnRecommendDataIds);
            } else {
                $grid->model();
            }
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.column_recommend_datas.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.column_recommend_datas.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.column_recommend_datas.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.column_recommend_datas.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            $grid->tools(function ($tools) {
                // $tools->batch(function ($batch) {
                //     // 批量删除按钮
                //     if (!\Gate::check('application.column_recommend_datas.batch_destroy')) {
                //         $batch->disableDelete();
                //     }
                // });
                $tools->append('<a href="javascript:void(0)" onclick="history.go(-1)" class="btn btn-default btn-sm" style="margin-right: 0px"> <i class="fa fa-arrow-left"></i>返回</a>');

            });

            // 添加按钮
            if (Admin::user()->cannot('application.column_recommend_datas.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('application.column_recommend_datas.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.column_recommend_datas.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.column_recommend_datas.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.column_recommend_datas.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '推荐数据名称')->sortable();
            $grid->column('title', '显示名称')->sortable();
            $grid->column('data.title', '数据类型')->sortable();
            $grid->column('resource_data_id', '数据')->display(function ($value) {
                $reasourceName = '';
                switch ($this->data['name']) {
                    case 'collist':
                        $reasourceName = Collist::where(['id' => $value])->value('title');
                        break;
                    case 'column0':
                        $reasourceName = Muticolumn::where(['id' => $value])->value('title');
                        break;
                    case 'column1':
                        $reasourceName = Muticolumn::where(['id' => $value])->value('title');
                        break;
                    case 'column2':
                        $reasourceName = Muticolumn::where(['id' => $value])->value('title');
                        break;
                    case 'vasset':
                        $reasourceName = Vasseti::where(['id' => $value])->value('title');
                        break;
                    case 'aasset':
                        $reasourceName = Vasseti::where(['id' => $value])->value('title');
                        break;
                    case 'iasset':
                        $reasourceName = Vasseti::where(['id' => $value])->value('title');
                        break;
                    default:
                        break;
                }
                if (empty($reasourceName)) {
                    $reasourceName = '';
                }
                return $reasourceName;
            });
            $grid->column('onclick', 'onclick事件')->sortable();
            $uploadConfig = config('custom.base.upload.column_recommend_data');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('img', '图片')->image($host);
            $grid->column('order', '排序')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }

    /**
     * 根据数据源类型的不同获取其下面的数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getReasoureByDataType(Request $request)
    {
        $dataId    = $request->get('q');
        $returnData = [];

        $data = Data::where(['id' => $dataId])->first();
        $result = json_decode($data->datasrc,true);
        // if (is_array($result)) {
        //     $table = $result['table'];
        //     $bool = Schema::hasTable($table);
        //     if ($bool) {
        //         $returnData = DB::table($table)->get(['name','id'])->toArray();
        //     }
        // }
        // 检查表是否存在
        if (!empty($data)) {
            $dataName = $data->name;
            //  如果推荐模板类型为0, 则获取模板相关数据
            if ($dataName ==='collist'){
                $returnData = Collist::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
            }elseif($dataName === 'column0') {
                $returnData = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
                // 如果推荐模板类型为1, 则获取栏目列表数据
            } elseif ($dataName === 'column1') {
                $returnData = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
            } elseif ($dataName === 'tag') {
                $returnData = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
            } elseif ($dataName === 'category') {
                $returnData = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
            } elseif ($dataName === 'arealist') {
                $returnData = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
            } elseif ($dataName === 'topbar') {
                $returnData = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
            } elseif ($dataName === 'vasset') {
                $returnData = Vasseti::get(['title', 'id'])->toArray();
            } elseif ($dataName === 'aasset') {
                $returnData = Vasseti::get(['title', 'id'])->toArray();
            } elseif ($dataName === 'iasset') {
                $returnData = Vasseti::get(['title', 'id'])->toArray();
            } elseif ($dataName === 'poster') {
                $returnData = Vasseti::get(['title', 'id'])->toArray();
            } elseif ($dataName === 'sp') {
                $returnData = Vasseti::get(['title', 'id'])->toArray();
            } elseif ($dataName === 'ogroup') {
                $returnData = Vasseti::get(['title', 'id'])->toArray();
            } elseif ($dataName === 'sgroup') {
                $returnData = Vasseti::get(['title', 'id'])->toArray();
            } elseif ($dataName === 'column_fun') {
                $returnData = ColumnFun::get(['title', 'id'])->toArray();
            }
        }
        return $returnData;

    }
    /**
     * ajax根据数据类型获取数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getReasourceData($dataId, Request $request)
    {
        $data = Data::where(['id' => $dataId])->first();
        if (empty($data)) {
            return response()->json(['content' => '无此数据类型!', 'status' => false]);
        }
        $datas    = [];
        $dataName = $data->name;
        //  如果推荐模板类型为0, 则获取模板相关数据
        if ($dataName ==='collist'){
            $datas = Collist::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        }elseif($dataName === 'column0') {
            $datas = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
            // 如果推荐模板类型为1, 则获取栏目列表数据
        } elseif ($dataName === 'column1') {
            $datas = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        } elseif ($dataName === 'tag') {
            $datas = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        } elseif ($dataName === 'category') {
            $datas = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        } elseif ($dataName === 'arealist') {
            $datas = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        } elseif ($dataName === 'topbar') {
            $datas = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        } elseif ($dataName === 'vasset') {
            $datas = Vasseti::get(['title', 'id'])->toArray();
        } elseif ($dataName === 'aasset') {
            $datas = Vasseti::get(['title', 'id'])->toArray();
        } elseif ($dataName === 'iasset') {
            $datas = Vasseti::get(['title', 'id'])->toArray();
        } elseif ($dataName === 'poster') {
            $datas = Vasseti::get(['title', 'id'])->toArray();
        } elseif ($dataName === 'sp') {
            $datas = Vasseti::get(['title', 'id'])->toArray();
        } elseif ($dataName === 'ogroup') {
            $datas = Vasseti::get(['title', 'id'])->toArray();
        } elseif ($dataName === 'sgroup') {
            $datas = Vasseti::get(['title', 'id'])->toArray();
        } elseif ($dataName === 'column_fun') {
            $datas = ColumnFun::get(['title', 'id'])->toArray();
        }

        return response()->json(['content' => $datas, 'status' => true]);
    }
}
